from flask import Flask, abort, render_template
from flask_session import Session
from flask_sqlalchemy import SQLAlchemy
import sys
import requests
import random
import keys

# Init ####################################################################
app = Flask(__name__)

app.secret_key = b'\x7f\x0e\x9b\xd8\xd5\xd8\x8f\xfa\xac\x1a\x026\xfe\xdf\xa2r'

app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
app.config['SQLALCHEMY_DATABASE_URI'] = keys.sql_uri
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

Session(app)
db = SQLAlchemy(app)

# Models ##################################################################
class UserList(db.Model):
    __tablename__ = 'testtable'
    userid = db.Column(db.Integer, nullable=False, primary_key=True)
    username = db.Column(db.String(100), nullable=False)

# Routes ##################################################################
@app.route('/')
def root():
    #return 'OK'
    str_key = '{}'.format(keys.sql_uri)
    str_port = '{}'.format(port)
    return render_template('index.html', str_key=str_key, str_port=str_port)


@app.route('/testlb')
def testlb():
    response_server = 'http://127.0.0.1:{}'.format(port)
    response_data = requests.get('http://127.0.0.1:{}/show'.format(port)).content.decode('utf-8')
    return render_template('testlb.html', response_server=response_server, response_data=response_data)


@app.route('/show')
def show():
    return ('{}'.format(UserList.query.filter_by(userid=random.randint(1, 5)).first().username))


# health check for load balancer
@app.route('/available')
def available():
    return 'yes'


if __name__ == '__main__':
    try:
        port = int(sys.argv[1])
    except IndexError:
        port = 5000
    print ('running on port %d' % port)
    app.run(port=port)

